<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<%@ page import="java.util.Date"%>
<% String formId = "form_" + new Date().getTime();
   String gridId = "grid_" + new Date().getTime();
   String path = request.getContextPath()+request.getServletPath().substring(0,request.getServletPath().lastIndexOf("/")+1);
%>
<script type="text/javascript" src="<%=request.getContextPath() %>/lib/uplodifyh5/event_common.js"></script>
<script type="text/javascript">
$(function () {
	var contents_dep = [{title:'请选择', value: ''}];
	var grid = $('[data-role="wardGrid"]');
    var form = $("[name='wardForm']");
	PageLoader = {
	    initSearchPanel:function() {
	    	 // 初始化科室列表
	    	 initeDepList("","depCodeID",form) ;
	    },
	    initGridPanel: function(){
	         var self = this;
	         var width = 180;
	         return grid.grid({
	                identity:"wardCode",
	                buttons: [
	                        {content: '<button class="btn btn-primary" type="button"><span class="glyphicon glyphicon-plus"><span>添加</button>', action: 'add'},
	                        {content: '<button class="btn btn-success" type="button"><span class="glyphicon glyphicon-edit"><span>修改</button>', action: 'modify'},
	                        {content: '<button class="btn btn-danger" type="button"><span class="glyphicon glyphicon-remove"><span>删除</button>', action: 'delete'},
	                        {content: '<button class="btn btn-success" type="button"><span class="glyphicon glyphicon-cloud-upload"><span>批量导入</button>', action: 'import'}
	                    ],
	                url:"${pageContext.request.contextPath}/Ward/pageJson.dhc",
	                columns: [
								 { title: '显示顺序', name: 'wardOrder', width: width},
		                     	 { title: '病区编码', name: 'wardCode', width: width},
		                     	 { title: '病区描述', name: 'wardDesc', width: width},
		                         { title: '所属科室', name: 'depName', width: width},
		                         { title: '病区描述', name: 'wardResume', width: width},
		                         { title: '操作', width: 120, render: function (rowdata, name, index)
	                                 {	
	                                     var h = "<a href=\"javascript:openWardDetailsPage("+JSON.stringify(rowdata).replace(/\"/g,"\'")+")\"><span class=\"glyphicon glyphicon glyphicon-eye-open\"></span>查看</a> ";
	                                     return h;
	                                 }
		                          }
	                ]
	         }).on({
	                   'add': function(){
	                       self.add($(this));
	                   },
	                   'modify': function(event, data){
	                	   var item = data.item;
	                        var indexs = data.data;
	                        var $this = $(this);
	                        if(indexs.length == 0){
	                            drgUI.warning('请选择一条记录进行修改!');
	                            return;
	                        }
	                        if(indexs.length > 1){
	                            drgUI.warning('只能选择一条记录进行修改!');
	                            return;
	                        }
	                       self.modify(data.item[0],indexs[0], $this);
	                    },
	                   'delete': function(event, data){
	                        var indexs = data.data;
	                        var $this = $(this);
	                        if(indexs.length == 0){
	                            drgUI.warning('请选择要删除的记录!');
	                            return;
	                        }
	                        var remove = function(){
	                            self.remove(indexs, $this);
	                        };
	                        drgUI.confirm({
	                            content: '确定要删除所选记录吗?',
	                            callSure: remove
	                        });
	                   },
	                   'import' : function(event, data) {
							 $('#uploadifive-wardImport input[type="file"]:last').click() ; 
						},
	         });
	    },
	    add: function(grid){
	        var self = this;
	        var dialog = $('<div class="modal fade"><div class="modal-dialog">'
	        	+'<div class="modal-content"><div class="modal-header"><button type="button" class="close" '
	        	+'data-dismiss="modal" aria-hidden="true">&times;</button>'
	        	+'<h4 class="modal-title">新增</h4></div><div class="modal-body">'
	        	+'<p>One fine body&hellip;</p></div><div class="modal-footer">'
	        	+'<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>'
	        	+'<button type="button" class="btn btn-success" id="save">保存</button></div></div>'
	        	+'</div></div>');
	        $.get('<%=path%>ward-add.jsp').done(function(html){
	            dialog.modal({
	                keyboard:false
	            }).on({
	                'hidden.bs.modal': function(){
	                    $(this).remove();
	                }
	            }).find('.modal-body').html(html);
	            self.initPage(dialog.find('form'));
	        });
	        dialog.find('#save').on('click',{grid: grid}, function(e){
	              if(!Validator.Validate(dialog.find('form')[0],3))return;
	              var wardOrder = $("#wardOrderID").val();
	              var wardCode = $("#wardCodeID").val();
	              $.post('${pageContext.request.contextPath}/Ward/isWardOrderExist.dhc',
	            		{"wardOrder":wardOrder}).done(function(result){
	            	  if(result){
	            		  drgUI.error('病区顺序已存在，请重新输入!');
	            		  return ;
	            	  } else{ 
	    	              $.post('${pageContext.request.contextPath}/Ward/isWardCodeExist.dhc',
	    	            		  {"wardCode":wardCode}).done(function(result){
	    	            	  if(result.data){
	    	            		  drgUI.error('病区编码已存在，请重新输入!');
	    	            	  } else{ 
	    	            		   $.post('${pageContext.request.contextPath}/Ward/add.dhc', dialog.find('form').serialize()).done(function(result){
	    	   	                   if(result.success ){
	    	   	                        dialog.modal('hide');
	    	   	                        e.data.grid.data('koala.grid').refresh();
	    	   	                    	 drgUI.success('保存成功!');
	    	   	                    }else{
	    	   	                     drgUI.error(result.actionError);
	    	   	                    }
	    	   	              	 });
	    	            	  }
	    	              });
	            	  }
	              });
	        });
	    },
	    modify: function(item,id, grid){
	        var self = this;
	        var dialog = $('<div class="modal fade"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h4 class="modal-title">修改</h4></div><div class="modal-body"><p>One fine body&hellip;</p></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">取消</button><button type="button" class="btn btn-success" id="save">保存</button></div></div></div></div>');
	        $.get('<%=path%>ward-update.jsp').done(function(html){
	               dialog.find('.modal-body').html(html);
	               self.initPage(dialog.find('form'));
	               dialog.find('#wardCodeID').val($.trim(item.wardCode));
	               dialog.find('#wardCodeID_hidden').val($.trim(item.wardCode));
	               dialog.find('#wardDescID').val($.trim(item.wardDesc));
	               dialog.find('#wardResumeID').val($.trim(item.wardResume));
	               dialog.find("#updateDepGroupCodeID").setValue(item.depGroupCode);
	               dialog.find("#wardOrderID").val(item.wardOrder);
	               // 异步加载导致赋值失败
	               dialog.find("#updateDepCodeID").setValue(item.depCode);
	               dialog.find('#idID').val(id);
	               dialog.find('#versionID').val(item.version);
	               dialog.modal({
	                    keyboard:false
	                }).on({
	                    'hidden.bs.modal': function(){
	                        $(this).remove();
	                    }
	                });
	                dialog.find('#save').on('click',{grid: grid}, function(e){
	                	if(!Validator.Validate(dialog.find('form')[0],3))return;
	                	 $.post('${pageContext.request.contextPath}/Ward/isWardOrderExist.dhc',
	                			 {"wardOrder":dialog.find("#wardOrderID").val(),
	                		 	  "wardCode": dialog.find('#wardCodeID').val()
	                			 }).done(function(result){
		                				if(result){
		                					drgUI.error('病区显示顺序已存在！')
		                				}else{
		            	                    $.post('${pageContext.request.contextPath}/Ward/update.dhc?id='+id, 
		            	                    		dialog.find('form').serialize()).done(function(result){
		            	                        if(result.success){
		            	                            dialog.modal('hide');
		            	                            e.data.grid.data('koala.grid').refresh();
		            	                            drgUI.success('保存成功!');
		            	                        }else{
		            	                            drgUI.error(result.actionError);
		            	                        }
		            	                    });
		                				}
	                	  });
	                });
	        });
	    },
	    initPage: function(form){
	              form.find('.form_datetime').datetimepicker({
	                   language: 'zh-CN',
	                   format: "yyyy-mm-dd",
	                   autoclose: true,
	                   todayBtn: true,
	                   minView: 2,
	                   pickerPosition: 'bottom-left'
	               }).datetimepicker('setDate', new Date());//加载日期选择器
	               form.find('.select').each(function(){
	                    var select = $(this);
	                    var idAttr = select.attr('id');
	                    var content = [] ;
	                    if( idAttr.indexOf("DepCodeID") > 0 ) {
	                    	content = contents_dep ;
	                    }
	                    select.select({
	                        title: "请选择",
	                        contents: content
	                    }).on('change', function() {
	                        form.find('#'+ idAttr + '_').val($(this).getValue()) ;
	                        form.find('#'+ idAttr + '_').focus();
	                        form.find('#'+ idAttr + '_').blur();
	                        if(idAttr == "addDepGroupCodeID" ) {
	                        	// 切换时下级下拉列表赋空值
	                        	if($(this).getValue() != "") {
	                        		form.find("#addParDepCodeID").setValue("");
	                        	}
	                        	initeDepList($(this).getValue(),"addParDepCodeID",form) ;
	                        } else if( idAttr == "updateDepGroupCodeID" ) {
	                        	if($(this).getValue() != "") {
	                        		form.find("#updateDepCodeID").setValue("");
	                        	}
	                        	initeDepList($(this).getValue(),"updateDepCodeID",form) ;
	                        }
	                    });
	               });
	    },
	    remove: function(ids, grid){
	    	var data = [{ name: 'wardCodes', value: ids.join(',') }];
	    	$.post('${pageContext.request.contextPath}/Ward/delete.dhc', data).done(function(result){
	                        if(result.success){
	                            grid.data('koala.grid').refresh();
	                            drgUI.success('删除成功!');
	                        }else{
	                            drgUI.error( result.result);
	                        }
	    	});
	    } 
	}
	
	PageLoader.initSearchPanel();
	PageLoader.initGridPanel();
	
	// 下载按钮
	var downloadBtn = '<div class="btn-clickable">' ;
	downloadBtn+='<a href="download/ward.xlsx" class="link text-sm" style = "text-decoration:none;color:#fff">' ;
	downloadBtn+='<i class="fa fa-download"></i>&nbsp;下载模版' ;
	downloadBtn+='</a>' ;
	downloadBtn+='</div>' ;
	$(<%=gridId%>).find("thead > tr > th").append(downloadBtn) ;
	
	form.find('#search').on('click', function(){
            if(!Validator.Validate(document.getElementById("<%=formId%>"),3))return;
            var params = {};
            form.find('input').each(function(){
                var $this = $(this);
                var name = $this.attr('name');
                if(name){
                    params[name] = $this.val();
                }
            });
            $('[data-role="wardGrid"]').getGrid().search(params);
        });
	/**
	 * depCode  科室编码
	 * selectId 下拉列表ID
	 * form 	表单
	 */
	function initeDepList(depGroupCode,selectId,form) {
		contents_dep = [{title:'请选择', value: ''}];
		$.ajax({  
	         type : "post",  
	          url : '${pageContext.request.contextPath}/Ward/findDepByWardCode.dhc',
	          data : {
					'parDepGroupCode':depGroupCode
				},  
	          async : false,  
	          success : function(result){  
	            if(result.success ) {
		            var depAll = result.data;
		            $.each(depAll,function(i,n) {
		             	contents_dep.push({title:n.depDesc, value:n.depCode});
		        	});
		            form.find('#'+selectId+'').select({
				        title: "请选择" ,
				        contents: contents_dep
				    }).on('change',function() {
				        form.find('#'+selectId+'_').val($(this).getValue());
				    });
		          }
	          }  
	     });
	}
	
	// 插件初始化
    $('#'+tabId+' #wardImport').uploadifive({
		'uploadScript' : contextPath + '/fileUpload/filesUpload.dhc',
        'height': 37,
        'width' :140,
        'auto'  : true,//是否自动开始
        'uploadLimit' : 10, //一次同步上传的文件数目     
        'fileSizeLimit' : '500MB', //单个文件大小，0为无限制，可接受KB,MB,GB等单位的字符串值     
        'queueSizeLimit' : 100, //队列中同时存在的文件个数限制
        'fileObjName':'file',
        'removeCompleted': false,  //是否完成后移除序列，默认为true
        'removeTimeout' : '5',  //上传完成后队列多长时间后消失。默认 3秒    需要：removeCompleted : true,时使用
        'buttonText' : '<i class="fa fa-folder-open fa-lg"></i>&nbsp;&nbsp;费用子项上传',
        'fileType' : '*.xls; *.xlsx; *.xml; *.dbf',//允许上传的文件格式
        'multi'    : true,//是否支持多文件上传
        'method'   :'post',//提交方式
        'debug':false,
        //当点击文件队列中文件的关闭按钮或点击取消上传时触发
        'onCancel': function(){ },
      	//返回一个错误，选择文件的时候触发  
        'onSelectError':  function(){
        	  drgUI.error('文件上传失败！');
        },
      	//检测FLASH失败调用  
        'onFallback':function(){  
            drgUI.error('浏览器检测不到兼容版本的HTML5！');
        }, 
        'onUpload': function(filesToUpload) {
        	$("#uploadifive-wardImport-queue").css("display","none") ;
        },
        'onUploadError' : uploadify_onUploadError,
        'onQueueComplete':function(queueData){
        	$.post(contextPath+'/fileUpload/wardImport.dhc').done(function(result){
        		var message = "" ;
        		if(result.success) {
        			message = result.data ;
        			grid.data('koala.grid').refresh();
        		} else {
        			message = "保存失败" ;
        		}
        		drgUI.alert(message,function(){
        			$('[data-role="wardGrid"]').grid('refresh');
        		});
        	});
        }
    });
 	$("#uploadifive-wardImport").css("display","none") ;
});
var openWardDetailsPage = function(rowdata){
    var dialog = $('<div class="modal fade"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h4 class="modal-title">查看</h4></div><div class="modal-body"><p>One fine body&hellip;</p></div><div class="modal-footer"><button type="button" class="btn btn-info" data-dismiss="modal">返回</button></div></div></div></div>');
    $.get('<%=path%>ward-view.jsp').done(function(html){
           dialog.find('.modal-body').html(html);
           rowdata = JSON.parse(JSON.stringify(rowdata).replace(/\'/g,"\""));
           dialog.find("#wardCodeID").html(rowdata.wardCode);
           dialog.find("#wardDescID").html(rowdata.wardDesc);
           dialog.find("#depGroupDescID").html(rowdata.depGroupDesc);
           dialog.find("#depNameID").html(rowdata.depName);
           dialog.find("#wardResumeID").html(rowdata.wardResume!=null?rowdata.wardResume!=""?rowdata.wardResume:"无":"无");
            dialog.modal({
                keyboard:false
            }).on({
                'hidden.bs.modal': function(){
                    $(this).remove();
                }
            });
    });
}



</script>
</head>
<body>
<div style="width:98%;margin-right:auto; margin-left:auto; padding-top: 15px;">
<!-- search form -->
<%-- <form name="wardForm" id=<%=formId%> target="_self" class="form-horizontal">
<table border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td>
          <div class="form-group">
          <label class="control-label" style="width:100px;float:left;">病区名称:&nbsp;</label>
            <div style="margin-left:15px;float:left;">
            <input name="wardDesc" class="form-control" type="text" style="width:180px;" id="wardDescID"  />
        </div>
          <label class="control-label" style="width:100px;float:left;">所属科室:&nbsp;</label>
          <div style="margin-left:15px;float:left;">
		      <div class="btn-group select" id="depCodeID"></div>
		      <input type="hidden" id="depCodeID_" name="depCode" />
	      </div>
        </div>
            </div>
            </td>
       <td style="vertical-align: bottom;"><button id="search" type="button" style="position:relative; margin-left:35px; top: -15px" class="btn btn-primary"><span class="glyphicon glyphicon-search"></span>&nbsp;查询</button></td>
  </tr>
</table>	
</form> --%>
<form name="wardForm" id=<%=formId%> target="_self" class="form-horizontal">
	<div class="container-fluid">
	<div class="row">
		<div class="form-group col-md-4">
			<label>病区名称:&nbsp;</label>
            <input name="wardDesc" class="form-control" type="text" style="width:180px;" id="wardDescID"  />
		</div>
		<div class="form-group  col-md-3">
			<label>所属科室:&nbsp;</label>
		      <div class="btn-group select" id="depCodeID"></div>
		      <input type="hidden" id="depCodeID_" name="depCode" />
		</div>
		<div class="form-group  col-md-1">
			<button id="search" type="button" style="" class="btn btn-primary"><span class="glyphicon glyphicon-search"></span>&nbsp;查询</button>
		</div>
	</div>
	</div>
</form>
<!-- grid -->
<div id=<%=gridId%> data-role="wardGrid" ></div>
</div>
<!-- 医师数据导入 --><!--  -->
<div><input id="wardImport" type="file" name="wardImport" style="display: none;"/></div>
</body>
</html>
